package org.mech.sefer.entity.dao;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;

import javax.annotation.Resource;

import org.hibernate.SessionFactory;
import org.mech.sefer.entity.model.AbstractEntity;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * <p>
 * The AbstractDao that uses spring dao support to work with session factory
 * </p>
 * <p>
 * Date: 7.5.2012 13:49:12
 * </p>
 * 
 * @param <E>
 *            the entity
 * @author martin.krajc
 */
public abstract class AbstractDao<E extends AbstractEntity> extends
		HibernateDaoSupport implements Dao<E> {

	private final Class<E> persistentClass;

	@SuppressWarnings("unchecked")
	public AbstractDao() {
		this.persistentClass = (Class<E>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}

	protected Class<E> getPersistentClass() {
		return persistentClass;
	}

	@Override
	public E findById(final Serializable id) {
		return getHibernateTemplate().get(getPersistentClass(), id);
	}

	@Override
	public void saveOrUpdate(final E entity) {
		getHibernateTemplate().saveOrUpdate(entity);
	}

	@Override
	public void saveOrUpdate(final Collection<E> entities) {
		getHibernateTemplate().saveOrUpdateAll(entities);
	}

	@Override
	public void delete(final E entity) {
		getHibernateTemplate().delete(entity);
	}

	@Override
	public void delete(final Collection<E> entities) {
		getHibernateTemplate().deleteAll(entities);
	}

	@Resource(name = "defaultSessionFactory")
	public void setDefaultSessionFactory(final SessionFactory sessionFactory) {
		super.setSessionFactory(sessionFactory);
	}

}
